package com.yaoyong.yy_demo.module.rabbitmq.routing;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import com.yaoyong.yy_demo.module.rabbitmq.util.ConnectionUtil;

public class Consumer2 {

    private final static String EXCHANGE_NAME = "test_exchange_direct";

    public static void main(String[] argv) throws Exception {

        // 获取到连接以及mq通道
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
        // 声明临时队列,发完消息会自动删除
        String queue = channel.queueDeclare().getQueue();

        // 绑定队列到交换机,直接收路由键为red和black的消息
        channel.queueBind(queue, EXCHANGE_NAME, "red");
        channel.queueBind(queue, EXCHANGE_NAME, "black");

        // 同一时刻服务器只会发一条消息给消费者
        channel.basicQos(1);

        // 定义队列的消费者
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        };
        channel.basicConsume(queue, true, deliverCallback, consumerTag -> {
        });
    }
}